import { useRef, useEffect } from "react"
import { parseData } from "../../utils"
import * as echarts from "echarts"
import ReactMarkdown from "react-markdown"
import remarkBreaks from "remark-breaks"

const cnIndexList = "一二三四五六七八九十".split("")

const option = (dataX = [], dataY = []) => ({
  tooltip: {
    trigger: "axis",
    axisPointer: {
      type: "cross",
      crossStyle: {
        color: "#999"
      }
    }
  },
  // legend: {
  //   data: ['问题数量', '已解决']
  // },

  grid: {
    left: "6%",
    right: "6%",
    bottom: "16%"
  },
  xAxis: [
    {
      type: "category",
      data: dataX, //['评标管理', '物资仓储管理', '废旧物资管理','采购程序管理', '采购计划管理', '物资结算管理'],
      axisPointer: {
        type: "shadow"
      },
      axisTick: {
        alignWithLabel: true,
        show: false
      }
    }
  ],
  yAxis: [
    {
      type: "value",
      name: "问题数量",
      min: 0,
      // max: Math.max(...dataY1) + 3,
      // interval: 3,

      axisLabel: {}
    }
    // {
    //   type: 'value',
    //   name: '已解决',
    //   min: 0,
    //   // max: 50,
    //   // interval: 10,
    //   axisLabel: {

    //   }
    // }
  ],
  series: [
    {
      name: "问题数量",
      type: "bar",
      data: dataY,
      barWidth: "32px",
      itemStyle: {
        color: {
          type: "linear",
          x: 0, // 从左开始
          y: 0, // 从下开始
          x2: 0, // 到右结束
          y2: 1, // 到上结束
          colorStops: [
            {
              offset: 0,
              color: "rgba(0, 200, 255, 1)" // 起始颜色
            },
            {
              offset: 1,
              color: "rgba(58, 77, 233, 1)" // 结束颜色
            }
          ]
        }
      }
    }
  ]
})

const Management = ({ item = {}, index = 0, onPenDialog }) => {
  const {
    aspectName,
    summaryText,
    suggestions,
    dataSource,
    reasonAnalysis,
    chartData
  } = item
  // console.log("item", item)
  const chart = useRef()

  const myChart = useRef(null)
  useEffect(() => {
    if (chart.current) {
      const {
        years = ["2021", "2022", "2023", "2024"],
        issueCount = [5, 12, 4, 3]
      } = parseData(chartData)
      // console.log("data", parseData(chartData))

      if (!myChart.current) {
        myChart.current = echarts.init(chart.current)
      }
      myChart.current.setOption(option(years, issueCount))
    }
  }, [chartData])

  const renderText = (text) => {
    if (!text || text === "") return text

    // 处理特殊的**加粗语法（保持原有功能）
    if (text.includes("**")) {
      const lines = text.split("**")
      if (lines.length === 0) return text
      return lines.map((line, index) => {
        if (index % 2 === 1) {
          return (
            <span key={index} className="font-bold text-blue-500">
              {line}
            </span>
          )
        } else {
          return line
        }
      })
    }

    // 预处理文本，确保换行符被正确处理
    const processedText = text.replace(/\n/g, "  \n") // Markdown需要在行尾添加两个空格才能换行

    // 使用ReactMarkdown解析，添加remarkBreaks插件支持换行
    return (
      <div className="markdown-content">
        <ReactMarkdown remarkPlugins={[remarkBreaks]}>
          {processedText}
        </ReactMarkdown>
      </div>
    )
  }

  const hadnleClickButton = (type) => {
    // console.log("hadnleClickButton", type)
    onPenDialog(
      type,
      type === "source"
        ? dataSource
        : type === "reason"
        ? reasonAnalysis
        : suggestions
    )
  }

  return (
    <section className="mb-4 mx-5">
      <h3 className="text-lg font-bold mb-2">
        （{cnIndexList[index]}）{aspectName}{" "}
      </h3>
      <div className="px-5 py-3 hexagon">
        <h4 className="text-md font-bold">结论</h4>
        <div className="text-sm whitespace-pre-line">
          {renderText(summaryText)}
        </div>
      </div>
      <div ref={chart} className="w-full h-[300px]"></div>
      <footer className="flex justify-center text-sm">
        <div
          className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer z-20"
          onClick={() => hadnleClickButton("reason")}
        >
          原因
        </div>
        <div
          className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer z-20"
          onClick={() => hadnleClickButton("suggest")}
        >
          建议
        </div>
        <div
          className="py-1 px-5 rounded-4xl border mx-2 cursor-pointer z-20"
          onClick={() => hadnleClickButton("source")}
        >
          数据来源
        </div>
      </footer>
    </section>
  )
}

export default Management
